package com.boot.service.impl;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.boot.dao.CartDao;
import com.boot.entity.Cart;
import com.boot.entity.CartList;
import com.boot.entity.Product;
import com.boot.service.CartService;
import com.boot.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 购物车表(Cart)表服务实现类
 *
 * @author makejava
 * @since 2023-07-20 18:48:25
 */
@Service("cartService")
public class CartServiceImpl extends ServiceImpl<CartDao, Cart> implements CartService {

    /**
     * 服务对象
     */
    @Autowired
    private ProductService productService;


    /**
     * 用户端加入购物车
     * @param pid
     * @param uid
     * @param count
     */
    @Override
    public void addCart(Integer pid, Integer uid, Integer count) {
        try {
            Cart cart = this.query().eq("u_id", uid).eq("p_id",pid).one();
            // 存在则商品购物车数量+1
            cart.setPCount(cart.getPCount() + count);
            this.updateById(cart);
        } catch (MybatisPlusException e) {
            // 创建购物车
            Cart cart = new Cart()
                    .setUId(uid)
                    .setPId(pid)
                    .setPCount(count);
            // 保存购物车
            this.save(cart);
        }
    }

    @Override
    public List<CartList> showCartsByUid(Integer uid) {
        // 查出uid的所有的购物车
        List<Cart> carts = this.query().eq("u_id",uid).list();
        List<CartList> cartLists = new ArrayList<>();
        carts.forEach(cart -> {
            Product product = productService.queryOneOrAllProduct(cart.getPId()).get(0);
            cartLists.add(new CartList()
                    .setCId(cart.getId())
                    .setCover(product.getCover())
                    .setSubject(product.getProductName())
                    .setCount(cart.getPCount())
                    .setSubTotal(product.getPrice().multiply(new BigDecimal(cart.getPCount()))));
        });
        //System.out.println(cartLists);
        return cartLists;
    }
}

